<script setup>
import { ref, computed, onMounted, nextTick } from "vue";
import HeadComponents from "@/components/headComponents.vue";
import http from "@/utils/http";
import { ElMessage, ElScrollbar, ElBadge } from "element-plus";
import { marked } from "marked";
import DOMPurify from "dompurify";
import { format } from "date-fns";

// -------------------------- 1. 核心数据定义 --------------------------
const historyConversations = ref([]);
const activeConversation = ref({
  id: null,
  title: "",
  messages: [],
  isLoadingAI: false
});
const inputMessage = ref("");
const isSidebarCollapsed = ref(false);

// -------------------------- 2. 初始化：加载历史对话 --------------------------
onMounted(async () => {
  await loadHistoryConversations();
});

// 从后端加载历史对话
const loadHistoryConversations = async () => {
  try {
    const res = await http.get("/medical-history/");
    historyConversations.value = res.data.map(item => ({
      id: item.id,
      title: item.title.replace("疾病查询: ", ""),
      messages: JSON.parse(item.content),
      createTime: item.createdAt,
      updateTime: item.updatedAt
    }));
    console.log("历史对话数据：", historyConversations.value);
    if (historyConversations.value.length > 0) {
      switchConversation(historyConversations.value[0]);
    }
  } catch (err) {
    ElMessage.error("加载历史对话失败");
    console.error(err);
  }
};

// -------------------------- 3. 对话切换 --------------------------
const switchConversation = (conversation) => {
  console.log("切换的对话消息：", conversation.messages);
  activeConversation.value = {
    ...conversation,
    messages: [...conversation.messages],
    isLoadingAI: false
  };
  nextTick(() => scrollToBottom());
};

// -------------------------- 4. 新对话 --------------------------
const createNewConversation = () => {
  activeConversation.value = {
    id: null,
    title: "",
    messages: [],
    isLoadingAI: false
  };
  inputMessage.value = "";
};

// -------------------------- 5. 发送消息（完整合并版） --------------------------
const sendMessage = async () => {
  const userContent = inputMessage.value.trim();

  // 输入验证
  if (!userContent) {
    ElMessage.warning("请输入您的问题");
    return;
  }
  if (activeConversation.value.isLoadingAI) {
    ElMessage.info("AI正在回复，请稍候...");
    return;
  }

  // 1. 添加用户消息到当前对话
  const userMessage = {
    role: "user",
    content: userContent,
    time: format(new Date(), "HH:mm:ss")
  };
  activeConversation.value.messages.push(userMessage);
  inputMessage.value = "";
  scrollToBottom();

  // 2. 标记AI正在加载，添加占位消息
  activeConversation.value.isLoadingAI = true;
  const loadingMessageIndex = activeConversation.value.messages.length;
  activeConversation.value.messages.push({
    role: "ai",
    content: "AI正在思考...",
    time: format(new Date(), "HH:mm:ss")
  });
  scrollToBottom();

  try {
    // 3. 调用DeepSeek API获取AI回复
    const response = await fetch("https://api.deepseek.com/v1/chat/completions", {
      method: "POST",
      headers: {
        "Authorization": "Bearer sk-81a0f32b15174b37a3aa19c344601be7",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        model: "deepseek-chat",
        messages: [
          {
            role: "system",
            content: "你是专业医疗助手，用清晰易懂的语言回答医疗健康问题，支持Markdown格式。请提供准确、专业的医疗建议。"
          },
          { role: "user", content: userContent }
        ],
        stream: true
      })
    });

    if (!response.ok) {
      throw new Error(`API请求失败：${response.status} ${response.statusText}`);
    }

    // 4. 处理流式响应
    const reader = response.body.getReader();
    const decoder = new TextDecoder("utf-8");
    let buffer = "";
    let aiContent = "";

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split("\n");
      buffer = lines.pop() || "";

      for (const line of lines) {
        if (line.startsWith("data: ")) {
          const data = line.slice(6);
          if (data === "[DONE]") continue;

          try {
            const parsed = JSON.parse(data);
            const delta = parsed.choices?.[0]?.delta?.content;
            if (delta) {
              aiContent += delta;
              // 实时更新AI消息内容
              activeConversation.value.messages[loadingMessageIndex] = {
                role: "ai",
                content: aiContent,
                time: format(new Date(), "HH:mm:ss")
              };
              scrollToBottom();
            }
          } catch (e) {
            console.warn("解析流式数据失败：", e);
          }
        }
      }
    }

    // 5. AI回复完成后保存对话到后端
    const conversationData = {
      title: `疾病查询: ${userContent}`,
      content: JSON.stringify([...activeConversation.value.messages])
    };

    if (activeConversation.value.id) {
      // 更新已有对话
      await http.put(`/medical-history/${activeConversation.value.id}`, conversationData);
      // 更新历史列表中的对应对话
      const index = historyConversations.value.findIndex(conv => conv.id === activeConversation.value.id);
      if (index !== -1) {
        historyConversations.value[index] = {
          ...historyConversations.value[index],
          messages: [...activeConversation.value.messages],
          updateTime: new Date().toISOString()
        };
      }
      ElMessage.success("对话已更新");
    } else {
      // 创建新对话
      const saveRes = await http.post("/medical-history/", conversationData);
      if (!saveRes.data || !saveRes.data.id) {
        throw new Error("后端未返回ID，保存失败");
      }
      activeConversation.value.id = saveRes.data.id;
      // 添加到历史列表
      historyConversations.value.unshift({
        id: saveRes.data.id,
        title: userContent,
        messages: [...activeConversation.value.messages],
        createTime: saveRes.data.createdAt || new Date().toISOString()
      });
      ElMessage.success("对话已保存到历史记录");
    }

  } catch (err) {
    // 错误处理
    console.error("AI请求失败：", err);
    activeConversation.value.messages[loadingMessageIndex] = {
      role: "ai",
      content: `抱歉，查询失败：${err.message || "未知错误，请稍后重试"}`,
      time: format(new Date(), "HH:mm:ss")
    };
    ElMessage.error("对话处理失败：" + (err.message || "未知错误"));
  } finally {
    // 无论成功失败，都标记AI加载完成
    activeConversation.value.isLoadingAI = false;
    scrollToBottom();
  }
};

// -------------------------- 6. 工具函数 --------------------------
// Markdown解析（安全过滤）
const parseMarkdown = (content) => {
  if (!content) return "";
  marked.setOptions({
    gfm: true,
    breaks: true,
    headerIds: false,
    sanitize: false
  });
  const rawHtml = marked.parse(content);
  return DOMPurify.sanitize(rawHtml);
};

// 滚动到对话底部
const scrollToBottom = () => {
  nextTick(() => {
    const chatContainer = document.querySelector(".chat-content");
    if (chatContainer) {
      chatContainer.scrollTop = chatContainer.scrollHeight;
    }
  });
};

// 监听回车发送
const handleKeyDown = (e) => {
  if (e.key === "Enter" && !e.shiftKey) {
    e.preventDefault();
    sendMessage();
  }
};

// -------------------------- 7. 计算属性：格式化对话时间 --------------------------
const formatConversationTime = computed(() => (timeStr) => {
  try {
    const date = new Date(timeStr);
    return format(date, "MM-dd HH:mm");
  } catch {
    return "未知时间";
  }
});
</script>

<template>
  <div id="chat-container">
    <!-- 顶部导航 -->
    <HeadComponents />

    <div class="chat-layout">
      <!-- 左侧：历史对话列表（响应式折叠） -->
      <div class="chat-sidebar" :class="{ collapsed: isSidebarCollapsed }">
        <!-- 侧边栏头部：标题+新建按钮 -->
        <div class="sidebar-header">
          <h3>历史对话</h3>
          <el-button
              type="primary"
              size="small"
              icon="Plus"
              @click="createNewConversation"
          >
            新对话
          </el-button>
          <!-- 移动端折叠按钮 -->
          <el-button
              icon="Menu"
              size="small"
              class="collapse-btn"
              @click="isSidebarCollapsed = !isSidebarCollapsed"
          ></el-button>
        </div>

        <!-- 历史对话列表（带滚动） -->
        <ElScrollbar class="sidebar-scroll">
          <div
              class="conversation-item"
              v-for="(conv, idx) in historyConversations"
              :key="conv.id || idx"
              :class="{ active: activeConversation.id === conv.id }"
              @click="switchConversation(conv)"
          >
            <!-- 未读徽章（可选，需添加未读标记逻辑） -->
            <!-- <ElBadge v-if="conv.unread" :value="conv.unread" type="danger" size="small" /> -->
            <div class="conv-title">{{ conv.title }}</div>
            <div class="conv-time">{{ formatConversationTime(conv.createTime) }}</div>
          </div>
          <div class="empty-history" v-if="historyConversations.length === 0">
            暂无历史对话，开始新对话吧～
          </div>
        </ElScrollbar>
      </div>

      <!-- 右侧：当前对话区 -->
      <div class="chat-main">
        <!-- 对话内容区（带滚动） -->
        <ElScrollbar class="chat-content">
          <div class="chat-empty" v-if="activeConversation.messages.length === 0">
            <div class="empty-icon">💬</div>
            <div class="empty-text">请输入您的医疗问题，AI将为您提供专业解答</div>
            <div class="empty-hint">示例：发烧怎么办？高血压需要注意什么？</div>
          </div>

          <!-- 对话气泡列表 -->
          <div class="message-list">
            <div
                class="message-item"
                v-for="(msg, idx) in activeConversation.messages"
                :key="idx"
                :class="{ 'user-message': msg.role === 'user', 'ai-message': msg.role === 'ai' }"
            >
              <!-- 角色头像 -->
              <div class="message-avatar">
                <span v-if="msg.role === 'user'">用户</span>
                <span v-else>AI</span>
              </div>
              <!-- 消息内容（解析Markdown） -->
              <div class="message-content" v-html="parseMarkdown(msg.content)"></div>
              <!-- 消息时间 -->
              <div class="message-time">{{ msg.time }}</div>
            </div>
          </div>
        </ElScrollbar>

        <!-- 底部输入区 -->
        <div class="chat-input-area">
          <el-input
              v-model="inputMessage"
              placeholder="请输入您的医疗问题（支持Markdown）..."
              class="input-box"
              :disabled="activeConversation.isLoadingAI"
              @keydown="handleKeyDown"
              type="textarea"
              rows="3"
          ></el-input>
          <el-button
              type="primary"
              class="send-btn"
              @click="sendMessage"
              :loading="activeConversation.isLoadingAI"
          >
            {{ activeConversation.isLoadingAI ? "发送中..." : "发送" }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 全局布局 */
#chat-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 左右分栏布局 */
.chat-layout {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 左侧历史对话列表 */
.chat-sidebar {
  width: 320px;
  border-right: 1px solid #e5e7eb;
  background-color: #f9fafb;
  display: flex;
  flex-direction: column;
  transition: width 0.3s ease;
}

/* 左侧折叠样式（移动端） */
.chat-sidebar.collapsed {
  width: 0;
  overflow: hidden;
}

/* 侧边栏头部 */
.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.sidebar-header h3 {
  font-size: 16px;
  margin: 0;
}

.collapse-btn {
  display: none; /* 默认隐藏，移动端显示 */
}

/* 历史对话列表滚动区 */
.sidebar-scroll {
  flex: 1;
  padding: 8px;
  overflow-y: auto;
}

/* 历史对话项 */
.conversation-item {
  padding: 12px 16px;
  border-radius: 8px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.conversation-item:hover {
  background-color: #f3f4f6;
}

.conversation-item.active {
  background-color: #eff6ff;
  border-left: 3px solid #2563eb;
}

.conv-title {
  font-size: 14px;
  color: #111827;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.conv-time {
  font-size: 12px;
  color: #6b7280;
}

/* 空历史提示 */
.empty-history {
  padding: 40px 20px;
  text-align: center;
  color: #6b7280;
  font-size: 14px;
}

/* 右侧当前对话区 */
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 对话内容滚动区 */
.chat-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background-color: #ffffff;
}

/* 空对话提示 */
.chat-empty {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #6b7280;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 18px;
  margin-bottom: 8px;
}

.empty-hint {
  font-size: 14px;
  color: #9ca3af;
}

/* 对话气泡列表 */
.message-list {
  max-width: 800px;
  margin: 0 auto;
}

/* 消息项通用样式 */
.message-item {
  display: flex;
  margin-bottom: 16px;
  position: relative;
}

/* 用户消息（右对齐） */
.user-message {
  flex-direction: row-reverse;
}

/* AI消息（左对齐） */
.ai-message {
  flex-direction: row;
}

/* 头像 */
.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #374151;
  margin: 0 8px;
  flex-shrink: 0;
}

.user-message .message-avatar {
  background-color: #2563eb;
  color: white;
}

/* 消息内容气泡 */
.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 16px;
  line-height: 1.8;
  font-size: 14px;
  word-break: break-all;
}

.user-message .message-content {
  background-color: #2563eb;
  color: white;
  border-bottom-right-radius: 4px;
}

.ai-message .message-content {
  background-color: #f3f4f6;
  color: #374151;
  border-bottom-left-radius: 4px;
}

/* 消息时间 */
.message-time {
  font-size: 12px;
  color: #9ca3af;
  margin: 0 8px;
  align-self: flex-end;
  margin-bottom: 4px;
}

.user-message .message-time {
  text-align: right;
}

/* 底部输入区 */
.chat-input-area {
  padding: 16px;
  border-top: 1px solid #e5e7eb;
  background-color: #ffffff;
  display: flex;
  gap: 12px;
}

.input-box {
  flex: 1;
  border-radius: 8px !important;
  resize: none;
}

.send-btn {
  width: 100px;
  height: 100%;
  align-self: flex-end;
  border-radius: 8px !important;
}

/* 响应式适配（移动端） */
@media (max-width: 768px) {
  .chat-sidebar {
    position: absolute;
    height: 100%;
    z-index: 10;
  }

  .collapse-btn {
    display: block;
  }

  .message-content {
    max-width: 85%;
  }
}
</style>